<template>
  <div class="knowledge-container">
    <!-- 标签页 -->
    <div class="tabs-container">
      <el-tabs v-model="activeTab" class="knowledge-tabs">
        <el-tab-pane :label="t('knowledge.tabs.cloudDocument')" name="cloud" />
      </el-tabs>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="search-action-bar">
      <!-- <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文档名称或类型"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button class="filter-btn" @click="handleReset">重置</el-button>
        <el-button type="primary" class="search-btn" @click="handleSearch">
          搜索
        </el-button>
      </div> -->
      <div class="action-section">
        <el-button type="primary" class="upload-btn" @click="handleOpenUpload">
          <el-icon><Upload /></el-icon>
          {{ t("knowledge.actions.upload") }}
        </el-button>
      </div>
    </div>

    <!-- 文件列表表格 -->
    <div class="table-container">
      <el-table
        :data="fileList"
        border
        class="knowledge-table"
        :empty-text="t('knowledge.table.empty')"
      >
        <el-table-column
          prop="fileName"
          :label="t('knowledge.table.fileName')"
          sortable
        >
          <template #default="{ row }">
            <div
              class="file-name-cell"
              @click="() => clickViewDocument(row.tos_path)"
            >
              <el-icon class="file-icon"><Document /></el-icon>
              <span>{{ row.doc_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="doc_type"
          :label="t('knowledge.table.type')"
          sortable
        />
        <el-table-column :label="t('knowledge.table.fileStatus')">
          <template #default="{ row }">
            <!-- 根据status值显示不同状态 -->
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('knowledge.table.uploadTime')" sortable>
          <template #default="{ row }">
            {{ formatTime(row.create_time) }}
          </template>
        </el-table-column>
        <el-table-column
          :label="t('knowledge.table.actions')"
          width="200"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              size="small"
              :icon="Delete"
              circle
              :disabled="row.status == 5"
              @click="deleteFile(row)"
            />
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 上传组件 -->
    <UploadComponent
      ref="uploadRef"
      :multiple="true"
      :limit="10"
      :max-size="100"
      :tips="[
        '单个文件最大20MB',
        '支持上传多个文件',
        '支持格式：docx、pdf',
        '文件上传后需要等待训练为“已完成”'
      ]"
      :upload-api="handleUploadDocument"
      @cancel="handleUploadCancel"
    />
  </div>
</template>

<script setup lang="ts">
import { knowledgeApi } from "@/api/knowledge";
import { reportApi } from "@/api/report-api";
import type { KnowledgeDocument } from "@/api/types/knowledge";
import UploadComponent from "@/components/Upload/index.vue";
import router from "@/router";
import { message } from "@/utils/message";
import { Delete, Document, Upload } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref } from "vue";
import { useI18n } from "vue-i18n";

// 国际化
const { t } = useI18n();

// 响应式数据
const activeTab = ref("cloud");
const searchKeyword = ref("");
const fileList = ref<KnowledgeDocument[]>([]);
const loading = ref(false);
const uploadRef = ref();
// 获取状态类型（用于el-tag的type属性）
const getStatusType = (status: string | number) => {
  const statusNum = Number(status);
  switch (statusNum) {
    case 0:
      return "success"; // 已学习 - 绿色
    case 1:
      return "danger"; // 处理失败 - 红色
    case 5:
      return "info"; // 删除中 - 灰色
    default:
      return "warning"; // 学习中 - 橙色
  }
};

// 获取状态文案
const getStatusText = (status: string | number) => {
  const statusNum = Number(status);
  switch (statusNum) {
    case 0:
      return t("knowledge.status.aiLearningSuccess"); // 已学习
    case 1:
      return t("knowledge.status.aiLearningFailed"); // 处理失败
    case 5:
      return t("knowledge.status.aiDeleting"); // 删除中
    default:
      return t("knowledge.status.aiLearningInProgress"); // 学习中
  }
};

// 获取知识库文档列表
const fetchKnowledgeList = async (keyword?: string) => {
  try {
    loading.value = true;
    console.log("开始获取知识库文档列表，搜索关键字:", keyword || "无");

    const response = await knowledgeApi.getKnowledgeDocumentList();

    if (response.code === 200) {
      let filteredData = response.data;

      // 如果有搜索关键字，在前端进行过滤
      if (keyword && keyword.trim()) {
        console.log("执行前端搜索过滤，关键字:", keyword.trim());
        filteredData = response.data.filter(item => {
          const lowerKeyword = keyword.trim().toLowerCase();
          return (
            item.doc_name.toLowerCase().includes(lowerKeyword) ||
            item.doc_type.toLowerCase().includes(lowerKeyword)
          );
        });
        console.log(
          `搜索结果：从 ${response.data.length} 条记录中筛选出 ${filteredData.length} 条`
        );
      }

      fileList.value = filteredData;
      console.log("文档列表更新成功，共", filteredData.length, "条记录");
    } else {
      console.error("获取文档列表失败，服务器返回:", response.message);
      ElMessage.error(
        response.message || t("knowledge.messages.fetchListFailed")
      );
    }
  } catch (error) {
    console.error("获取知识库文档列表失败:", error);
    ElMessage.error(t("knowledge.messages.fetchListFailed"));
  } finally {
    loading.value = false;
    console.log("文档列表获取操作完成");
  }
};

// 搜索按钮点击处理函数
const handleSearch = async () => {
  console.log("用户点击搜索按钮，当前搜索关键字:", searchKeyword.value);

  if (!searchKeyword.value.trim()) {
    console.log("搜索关键字为空，获取所有文档");
    await fetchKnowledgeList();
  } else {
    console.log("开始执行搜索，关键字:", searchKeyword.value.trim());
    await fetchKnowledgeList(searchKeyword.value);
  }
};

// 重置按钮点击处理函数
const handleReset = async () => {
  console.log("用户点击重置按钮，清空搜索条件");

  // 清空搜索关键字
  searchKeyword.value = "";
  console.log("搜索关键字已重置为空");

  // 重新获取所有文档
  console.log("重新获取所有文档列表");
  await fetchKnowledgeList();

  console.log("重置操作完成");
};

// 删除文件方法
const deleteFile = async (row: KnowledgeDocument) => {
  try {
    // 确认删除操作
    await ElMessageBox.confirm(
      t("knowledge.messages.deleteConfirm", { fileName: row.doc_name }),
      t("knowledge.messages.deleteTitle"),
      {
        confirmButtonText: t("knowledge.messages.confirmDelete"),
        cancelButtonText: t("knowledge.messages.cancel"),
        type: "warning",
        confirmButtonClass: "el-button--danger"
      }
    );

    // 执行删除操作
    const response = await knowledgeApi.deleteKnowledgeDocument(row.doc_id);

    if (response.code === 200) {
      ElMessage.success(
        response.message || t("knowledge.messages.deleteSuccess")
      );
      // 删除成功后重新获取列表
      await fetchKnowledgeList();
    } else {
      ElMessage.error(response.message || t("knowledge.messages.deleteFailed"));
    }
  } catch (error) {
    // 用户取消删除或其他错误
    if (error !== "cancel") {
      console.error("删除文档失败:", error);
      ElMessage.error(t("knowledge.messages.deleteRetryFailed"));
    }
  }
};
// 格式化时间戳
const formatTime = (timestamp: number) => {
  return new Date(timestamp * 1000).toLocaleString();
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return "0 B";

  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const clickViewDocument = async (url: string) => {
  if (!url) {
    return message("文档url为空");
  }
  // 移出前两个/之前的数据
  const relaUrl = url.replace(/^[^/]+\//, "");
  console.log("relaUrl", relaUrl);
  const data = await knowledgeApi.presignedApi({ objectKey: `${relaUrl}` });
  console.log("aaaaa", data.data.fileAccessUrl);
  router.push({
    path: "/knowledge/document",
    query: {
      url: data.data.fileAccessUrl
    }
  });
};

// 打开上传弹窗
const handleOpenUpload = () => {
  uploadRef.value?.open();
};

// 自定义上传API函数
const handleUploadDocument = async (file: File) => {
  try {
    // 准备预签名URL的请求参数
    const params = {
      fileName: file.name,
      fileType: 3
    };

    // 获取预签名URL
    const presignedResponse = await reportApi.presignedApi(params);

    if (presignedResponse?.data?.presignedUrl) {
      // 第二步：使用fetch直接上传到预签名URL
      const uploadResponse = await fetch(
        presignedResponse?.data?.presignedUrl,
        {
          method: "PUT",
          body: file,
          // 详细日志：设置Content-Type为上传文件的类型，如果没有则使用默认类型
          headers: {
            "Content-Type": file?.type || "application/octet-stream"
          }
        }
      );
      console.log("mujin uploadResponse :>> ", uploadResponse);
      if (!uploadResponse.ok) {
        throw new Error(
          `上传失败: ${uploadResponse.status} ${uploadResponse.statusText}`
        );
      }
      console.log(
        "mujin uploadResponse :>> ",
        presignedResponse?.data?.fileAccessUrl
      );
      knowledgeApi.postKnowledgeDocument({
        tos_path: presignedResponse?.data?.objectKey,
        doc_name: file.name
      });
      return uploadResponse.body;
    }
  } catch (error) {
    console.error("文档上传失败:", error);
    throw error;
  }
};

// 上传成功回调
const handleUploadSuccess = (files: UploadFile[]) => {
  console.log("上传成功的文件:", files);
  ElMessage.success(
    t("knowledge.messages.uploadSuccess", { count: files.length })
  );

  // 刷新文档列表
  fetchKnowledgeList();
};

// 取消上传回调
const handleUploadCancel = () => {
  console.log("用户取消了上传");
};

// 组件挂载时获取数据
onMounted(() => {
  fetchKnowledgeList();
});
</script>

<style lang="scss" scoped>
.knowledge-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 120px);
  border-radius: 12px;
}

.tabs-container {
  margin-bottom: 20px;

  .knowledge-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 0;
    }

    :deep(.el-tabs__nav-wrap::after) {
      height: 1px;
      background-color: #f5f5f5;
    }
  }
}

.search-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 0;

  .search-section {
    display: flex;
    align-items: center;
    gap: 12px;

    .search-input {
      width: 300px;
    }

    .search-btn,
    .filter-btn {
      height: 32px;
    }
  }

  .action-section {
    .upload-btn {
      height: 32px;

      .el-icon {
        margin-right: 4px;
      }
    }
  }
}

.table-container {
  .knowledge-table {
    :deep(.el-table__header) {
      background-color: #fafafa;
    }

    .file-name-cell {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #409eff;
      cursor: pointer;

      .file-icon {
        color: #409eff;
        font-size: 16px;
      }
    }
  }
}
</style>
